import axios from 'axios'
import store from '@/store'
import router from "@/router";
import { ElLoading, ElMessage } from 'element-plus'

axios.defaults.baseURL = '/api'

/* 请求拦截器 */
axios.interceptors.request.use((config) => {
    // 添加token到header
    const token = store.getters.user.token
    if (token) {
        config.headers.jwt_auth = token;
        // config.headers.cookie = token
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

/* 响应拦截器 */
axios.interceptors.response.use((response) => {
    const { data = {} } = response
    if (data.code == 401) {

        if (router.currentRoute.value.path == '/Login') return;
        ElMessage.error('登录信息已失效，正在跳转至登录！')
        // 跳转首页
        router.push("/Login");
        return
    }
    if (data.code == 403) {
        ElMessage.error('用户未授权！')
        return
    }
    if (data.code == 500) {
        ElMessage.error(data.msg)
        return
    }
    return response.data
}, (error) => {
    // 处理响应错误
    if (error?.response?.data?.msg) ElMessage.error(error?.response?.data?.msg);
    return error;
});


var index = 0

const get = (url, params) => {
    return new Promise((resolve, reject) => {
        if (!params) {
            params = {};
        }
        // 加载中
        const loading = ElLoading.service({
            lock: true,
            background: 'rgba(0, 0, 0, 0)',
        })
        index++;
        axios.get(url, {
            params
        })
            .then(result => {
                resolve(result);
                index--;
                if (index <= 0) loading.close();
            })
            .catch((err => {
                reject(err);
                index--;
                if (index <= 0) loading.close();
            }))
    });
}
const post = (url, params) => {
    return new Promise((resolve, reject) => {
        if (!params) {
            params = {};
        }
        // 加载中
        const loading = ElLoading.service({
            lock: false,
            background: 'rgba(0, 0, 0, 0)',
        })
        index++;
        axios.post(url, params)
            .then(result => {
                resolve(result);
                index--;
                if (index <= 0) loading.close();
            })
            .catch((err => {
                reject(err);
                index--;
                if (index <= 0) loading.close();
            }))
    });
}

const getAndLoadData = async (url, params) => {
    let result = await get(url, params)
    return result?.data
}
const postAndLoadData = async (url, params) => {
    let result = await post(url, params)
    return result?.data
}

export default {
    get,
    getAndLoadData,
    post,
    postAndLoadData
}

